var express = require('express');
var router = express.Router();
//引入上传模块
let multer = require('multer')
let fs=require('fs')
//配置上传对象
let upload = multer({dest:"./public/upload"})
var sqlQuery=require('../../module/lcMysql')
var jiami=require('../../module/jiami')
//若使用中间件：1先定义中间件函数   2.使用中间件   router.use(函数名)

//进入个人信息页
router.get('/',async (req,res)=>{
    let sqlStr="select * from user where username=?"
    let result=await sqlQuery(sqlStr,[req.session.username])
    let sqlStr2="select * from role "
    let result2=await sqlQuery(sqlStr2)
    let options={
        user:result[0],
        roles:Array.from(result2)
    }
    res.render('user/userInfo.ejs',options)
})

//头像上传(仅传至服务器不做数据库操作)
router.post('/selfimgupload',upload.single('uploadImg'),async (req,res)=>{
    // let username = req.session.username;
    let result =await rename(req)
    console.log(result)
    //将改名后的结果，上传到数据库
    // let strSql = "update user set imgheader = ? where username = ?"
    // await sqlQuery(strSql,[result.imgUrl,username])
    res.json(result)
  })

  //将fs.rename封装成Promise对象
	var rename =function(req){
		return new Promise((resolve,reject)=>{
        var ele=req.file;
				var oldFile=ele.destination+"/"+ele.filename;	//指定旧文件
				var newFile=ele.destination+"/"+ele.filename+ele.originalname;	//指定新文件
				fs.rename(oldFile,newFile,function(err){
					if(err) {
						reject(err);
					}else{
						resolve({
                      msg:'ok',
                      imgUrl:"/upload/"+ele.filename+ele.originalname
                    })
					}

				});
		})
  }
  
  //修改个人信息
  router.post('/edit',async (req,res)=>{
    let obj=req.body
    let sqlStr='update user set imgheader=?,username=?,password=?,email=?,mobile=?,roleid=?,sex=?,userdesc=? where username=?'
    console.log(sqlStr);
    
    await sqlQuery(sqlStr,[obj.imgheader, obj.username,jiami(obj.password),obj.email,obj.mobile,obj.role,obj.sex,obj.desc,req.session.username])
    res.json({
      msg:"ok"
    })
  })
module.exports=router